package com.aiti.lulian.scheduled;

import com.aiti.base.core.utils.message.Message;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Message handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        StringBuilder message = new StringBuilder();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            message.append(errorMessage).append("，");
        });
        char c = message.charAt(message.length() - 1);
        if(c == '，'){
            message.deleteCharAt(message.length() - 1);
        }
        return Message.fail(message.toString());
    }

    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Message exceptionHandler(Exception e){
        return Message.fail(e.getMessage());
    }

    @ExceptionHandler(value =RuntimeException.class)
    @ResponseBody
    public Message runtimeExceptionHandler(Exception e){
        return Message.fail(e.getMessage());
    }
}
